import express from "express";
import fs from "fs";
import path from "path";
import multer from "multer";
import { fileURLToPath } from "url";
import db from "../db/db.js";
import csvDetail from "./csvDetail.js";
import dataToSQL from "./dataToSQL.js";
import excelDetail from "./excelDetail.js";

const uploadFile = express.Router();

// 将 ES 模块的路径转换为文件系统路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 设置上传文件的目录路径
const uploadDir = path.join(__dirname, "fileUpload");

// Multer 配置，用于处理上传文件并保存到指定目录
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        // 不存在文件保存目录就创建
        if (!fs.existsSync(uploadDir)) {
            fs.mkdirSync(uploadDir);
        }
        cb(null, uploadDir);
    },
    filename: (req, file, cb) => {
        const fileName = req.body.filename; // 从请求体中获取文件名参数
        // 如果请求体中没有提供文件名，则使用上传的文件原始名
        if (!fileName) {
            cb(null, file.originalname);
        } else {
            cb(null, fileName);
        }
    },
});

const upload = multer({ storage: storage });

function formatDateForMySQL(date) {
    return date.toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" }).replace("/", "-").replace("/", "-").replace(" ", "T");
    // return date.toISOString().slice(0, 19).replace('T', ' '); // 转换为 'YYYY-MM-DD HH:MM:SS'
}

function query(data) {
    data.id = Math.random().toString(36).slice(2, 9);
    data.time = formatDateForMySQL(new Date());
    data.timestamp = new Date().getTime();
    data.userName = "admin";
    return new Promise((resolve, reject) => {
        db.query(
            `
    INSERT INTO uploadFiles SET 
    id = ?, time = ?, timestamp = ?, userName = ?, fileName = ?, source = ?, remark = ?
    `,
            [data.id, data.time, data.timestamp, data.userName, data.filename, data.dataSource, data.remark],
            (err, results) => {
                if (err) {
                    reject(err);
                    console.log("账单数据写入失败！");
                } else {
                    console.log("账单数据写入成功！");
                }
            }
        );
    });
}

// 定义文件上传路由
uploadFile.post("/uploadFile", upload.single("file"), async (req, res) => {
    if (!req.file) {
        return res.status(400).send("No file uploaded");
    }
    try {
        const filePath = path.join(uploadDir, req.file.filename);
        const dataDetailRes = req.body.dataSource !== "custom" ? await csvDetail(filePath, req.body.dataSource) : await excelDetail(filePath);
        dataToSQL(dataDetailRes, req.body.dataSource);
        query(req.body);
        res.send(`File ${req.file.filename} uploaded successfully!`);
    } catch (error) {
        console.error(error);
        res.status(500).send("Error uploading file");
    }
});

export default uploadFile;
